package cn.ibizlab.core.authentication.domain;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;

import java.util.LinkedHashSet;

@Getter
@Setter
@JsonIgnoreProperties(value = "handler")
public class AuthUserImpl extends AuthUser implements UserDetails {

    @JsonIgnore
    @JSONField(serialize = false)
    private LinkedHashSet<GrantedAuthority> authorities;

    @JsonIgnore
    @JSONField(serialize = false)
    private String password;

    @JsonProperty("super_user")
    @JSONField(name = "super_user")
    @ApiModelProperty(value = "super_user", notes = "超级管理员")
    private Integer superUser;

    @JsonProperty("api_user")
    @JSONField(name = "api_user")
    @ApiModelProperty(value = "api_user", notes = "API用户")
    private Integer apiUser;

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isSuperUser() {
        return Integer.valueOf(1).equals(superUser);
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isApiUser() {
        return Integer.valueOf(1).equals(apiUser);
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public LinkedHashSet<GrantedAuthority> getAuthorities() {
        if(authorities == null && !ObjectUtils.isEmpty(this.getRoles())) {
            authorities = new LinkedHashSet<>();
            this.getRoles().forEach(system->{
                authorities.add(new SimpleGrantedAuthority(String.format("SYSTEM_%1$s",system.getDeploySystemId())));
                if(!ObjectUtils.isEmpty(system.getSystemId()))
                    authorities.add(new SimpleGrantedAuthority(String.format("SYSTEM_%1$s",system.getSystemId())));
                if(ObjectUtils.isEmpty(system.getRoles()))
                    return;
                system.getRoles().forEach(role->{
                    if(ObjectUtils.isEmpty(role.getAuthority()))
                        return;
                    if(role.getAuthority().equalsIgnoreCase("ROLE_SUPERADMIN")||role.getAuthority().equalsIgnoreCase("ROLE_APIUSERS"))
                        this.setSuperUser(1);
                    if(role.getAuthority().equalsIgnoreCase("ROLE_APIUSERS"))
                        this.setApiUser(1);
                    authorities.add(new SimpleGrantedAuthority(String.format("ROLE_%1$s",role.getRoleId())));
                    authorities.add(new SimpleGrantedAuthority(role.getAuthority()));
                    if(!ObjectUtils.isEmpty(system.getSystemId()))
                        authorities.add(new SimpleGrantedAuthority(String.format("ROLE_%1$s_%2$s",system.getSystemId(),role.getAuthority())));
                    if(!ObjectUtils.isEmpty(role.getAuthorities()))
                        role.getAuthorities().forEach(authGranted -> {
                            String authority = authGranted.getAuthority();
                            if(!ObjectUtils.isEmpty(authority)&&authority.indexOf(":")>=0)
                                authority=authority.split(":")[1];
                            if(!ObjectUtils.isEmpty(authority)) {
                                String[] args=authority.split("-");
                                if("OPPRIV".equals(authGranted.getPermissionType()) && args.length==4&&args[2].startsWith("Fetch")) {
                                    authorities.add(new SimpleGrantedAuthority(authority));
                                    args[2]=args[2].replace("Fetch","search");
                                    authority=String.join("-",args);
                                }
                                else if ("APPMENU".equals(authGranted.getPermissionType()) && args.length==4) {
                                    authorities.add(new SimpleGrantedAuthority(authority));
                                    authority=String.join("-",args[0],"APPMENU",args[1],args[2],args[3]);
                                }
                                authorities.add(new SimpleGrantedAuthority(authority));
                            }
                        });
                });
            });
        }
        return authorities;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public String getPassword() {
        return password;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
